import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@WebServlet(urlPatterns = "/download")
public class DownloadServlet extends HttpServlet {
   
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        count++;
        String fname = req.getParameter("filename");
        String path = getServletContext().getRealPath("/download/");
        FileInputStream in = new FileInputStream( path + fname);
        //resp.setContentType("text/html;");
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        resp.setContentType("multipart/form-data");
        //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        resp.setHeader("Content-Disposition", "attachment;fileName="+fname);
        ServletOutputStream out = resp.getOutputStream();
        byte[] buffer = new byte[1024*8];
        int len = 0;
        while((len=in.read(buffer))!=-1){
            out.write(buffer,0,len);
        }
        out.flush();
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
